package com.sskj.hangqing.ui.fragment;


import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.depth.bean.DepthData;
import com.sskj.depth.bean.IDepthData;
import com.sskj.depth.view.DepthMapView;
import com.sskj.hangqing.R;
import com.sskj.hangqing.R2;
import com.sskj.hangqing.bean.rxbus.MarketCoinBean;
import com.sskj.hangqing.presenter.DepthFragmentPresenter;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.WSFiveBean;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.util.CoinUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

@Route(path = RConfig.HANG_FRAGMENT_DEEPTH)
public class DepthFragment extends BaseFragment<DepthFragmentPresenter> {
    private static final long MAX_NUM = 30;
    @Autowired
    String code;
    @Autowired
    String qu;
    @Autowired
    boolean isBibi;
    @BindView(R2.id.tvBuyNumTitle)
    TextView tvBuyNumTitle;
    @BindView(R2.id.tvSellNumTitle)
    TextView tvSellNumTitle;
    @BindView(R2.id.tvPrice)
    TextView tvPrice;
    @BindView(R2.id.recyclerViewBuy)
    RecyclerView buyRecyclerView;
    @BindView(R2.id.recyclerViewSell)
    RecyclerView sellRecyclerView;
    @BindView(R2.id.depthMapView)
    DepthMapView depthMapView;
    private SlimAdapter sellSlimAdapter;
    private SlimAdapter buySlimAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.hang_fragment_depth;
    }

    @Override
    public DepthFragmentPresenter getPresenter() {
        return new DepthFragmentPresenter();
    }

    @Override
    public void initView() {
        ARouter.getInstance().inject(this);

        tvBuyNumTitle.setText(String.format(getString(R.string.hangqingtradeFragment2), CoinUtil.getLCode(code)));
        tvSellNumTitle.setText(String.format(getString(R.string.hangqingtradeFragment2), CoinUtil.getLCode(code)));
        tvPrice.setText(String.format(getString(R.string.hangqingtradeFragment1),CoinUtil.getRCode(code)));
        initRecy();
        depthMapView.mPriceLimit = CoinUtil.getPriceKeepNum(code);
        depthMapView.mVolumeLimit = CoinUtil.getNumKeepNum(code);

    }

    @Override
    public void initData() {
        mPresenter.getData(code);
        mPresenter.initSocket(code,isBibi);
        LiveDataBus.get().with(RxBusCode.CHANGE_MARKET_CODE, MarketCoinBean.class)
                .observe(this, this::changeCoin);
    }

    @SuppressWarnings("unchecked")
    private void initRecy() {
        sellRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        buyRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        buySlimAdapter = SlimAdapter.create().register(R.layout.hang_recy_item_deep_buy, new SlimInjector<WSFiveBean.FiveBean>() {
            @Override
            public void onInject(WSFiveBean.FiveBean data, IViewInjector injector, List<Object> payloads) {
                injector.text(R.id.tvOrderNum, buySlimAdapter.getData().indexOf(data) + 1 + "")
                        .text(R.id.tvPrice, data.getPrice())
//                        .textColor(R.id.tvPrice, ContextCompat.getColor(App.INSTANCE, BuySellEnum.BUY.getColorRes()))
                        .text(R.id.tvNum, data.getTotalSize())
                        .with(R.id.bibiProgressbar, view -> {
                            ProgressBar progressBar = (ProgressBar) view;
                            progressBar.setProgressDrawable(ContextCompat.getDrawable(App.INSTANCE, R.drawable.hang_progress_green));
                            progressBar.setProgress(100 - data.getPercent());
                        })
                ;
            }
        }).attachTo(buyRecyclerView).updateData(new ArrayList());
        sellSlimAdapter = SlimAdapter.create().register(R.layout.hang_recy_item_deep_sell, new SlimInjector<WSFiveBean.FiveBean>() {
            @Override
            public void onInject(WSFiveBean.FiveBean data, IViewInjector injector, List<Object> payloads) {
                injector.text(R.id.tvOrderNum, sellSlimAdapter.getData().indexOf(data) + 1 + "")
//                        .textColor(R.id.tvPrice, ContextCompat.getColor(App.INSTANCE, BuySellEnum.SELL.getColorRes()))
                        .text(R.id.tvPrice, data.getPrice())
                        .text(R.id.tvNum, data.getTotalSize())
                        .with(R.id.bibiProgressbar, view -> {
                            ProgressBar progressBar = (ProgressBar) view;
                            progressBar.setProgressDrawable(ContextCompat.getDrawable(App.INSTANCE, R.drawable.hang_progress_red));
                            progressBar.setProgress(data.getPercent());
                        })
                ;
            }
        }).

                attachTo(sellRecyclerView).

                updateData(new ArrayList());
        sellRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                if (recyclerView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE) {
                    buyRecyclerView.scrollBy(dx, dy);
                }
            }
        });
        buyRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                if (recyclerView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE) {
                    sellRecyclerView.scrollBy(dx, dy);
                }
            }
        });
    }

    public void changeCoin(MarketCoinBean marketCoinBean) {
        code = marketCoinBean.getCode();
        qu = marketCoinBean.getQu();
        tvBuyNumTitle.setText(String.format(getString(R.string.hangqingtradeFragment2), CoinUtil.getLCode(code)));
        tvSellNumTitle.setText(String.format(getString(R.string.hangqingtradeFragment2), CoinUtil.getLCode(code)));
        tvPrice.setText(String.format(getString(R.string.hangqingtradeFragment1),CoinUtil.getRCode(code)));

        mPresenter.getData(code);
        mPresenter.initSocket(code,isBibi);
    }


    public void updateUI(WSFiveBean data) {
        if (data == null || buySlimAdapter == null || depthMapView == null) {
            return;
        }
        Flowable.just(1)
                .subscribeOn(Schedulers.io())
                .flatMap(integer -> {
                    System.out.println(Thread.currentThread().getName());
                    WSFiveBean wsFiveBean = new WSFiveBean();
                    ArrayList<WSFiveBean.FiveBean> buyFiveBean = new ArrayList<>();
                    ArrayList<WSFiveBean.FiveBean> sellFiveBean = new ArrayList<>();
                    wsFiveBean.setCode(code);
                    wsFiveBean.setBids(buyFiveBean);
                    wsFiveBean.setAsks(sellFiveBean);
                    Flowable.fromIterable(data.getBids())
                            .take(MAX_NUM)
                            .map(fiveBean -> buyFiveBean.add(new WSFiveBean.FiveBean(fiveBean.getDoubleTotalSize(), fiveBean.getPrice(), code)))
                            .subscribe();
                    Flowable.fromIterable(data.getAsks())
                            .take(MAX_NUM)
                            .map(fiveBean -> sellFiveBean.add(new WSFiveBean.FiveBean(fiveBean.getDoubleTotalSize(), fiveBean.getPrice(), code)))
                            .subscribe();
                    calculatePercentAll(wsFiveBean);

                    Collections.reverse(data.getAsks());
                    Collections.reverse(data.getBids());
                    Flowable<List<IDepthData>> buyFlow = Flowable.fromIterable(data.getBids())
                            .map(fiveBean -> (IDepthData) new DepthData(fiveBean.getDoubleTotalSize() + "", fiveBean.getPrice()))
                            .toList()
                            .toFlowable();
                    Flowable<List<IDepthData>> sellFlow = Flowable.fromIterable(data.getAsks())
                            .map(fiveBean -> (IDepthData) new DepthData(fiveBean.getDoubleTotalSize() + "", fiveBean.getPrice()))
                            .toList()
                            .toFlowable();

                    return Flowable.zip(buyFlow, sellFlow, (buyData, sellData) -> {

                        SparseArray<Object> listSparseArray = new SparseArray<>();
                        listSparseArray.put(0, buyFiveBean);
                        listSparseArray.put(1, sellFiveBean);
                        listSparseArray.put(2, buyData);
                        listSparseArray.put(3, sellData);
                        return listSparseArray;
                    });
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(o -> {
                    System.out.println(getString(R.string.hangqing_depthFragment3) + Thread.currentThread().getName());
                    buySlimAdapter.updateData((List) o.get(0));
                    sellSlimAdapter.updateData((List) o.get(1));
                    if (depthMapView == null)
                        return;
                    depthMapView.setData((List<IDepthData>) o.get(2), (List<IDepthData>) o.get(3));
                }, e -> {
                });

    }

    private void calculatePercentAll(WSFiveBean wsFiveBean) {
        Double full = 0d;
        for (WSFiveBean.FiveBean bid : wsFiveBean.getBids()) {
            Double aDouble = Double.valueOf(bid.getDoubleTotalSize());
            if (aDouble > full) {
                full = aDouble;
            }
        }
        for (WSFiveBean.FiveBean ask : wsFiveBean.getAsks()) {
            Double aDouble = Double.valueOf(ask.getDoubleTotalSize());
            if (aDouble > full) {
                full = aDouble;
            }
        }
        for (WSFiveBean.FiveBean bid : wsFiveBean.getBids()) {
            Double aDouble = Double.valueOf(bid.getDoubleTotalSize());
            bid.setPercent((int) (aDouble / full * 100d));
        }

        for (WSFiveBean.FiveBean ask : wsFiveBean.getAsks()) {
            Double aDouble = Double.valueOf(ask.getDoubleTotalSize());
            ask.setPercent((int) (aDouble / full * 100d));
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
